package com.dayaokeji.rhythmschoolstudent.client.home.course.ranking;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.ApiConstantKt;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.course.ranking.adapter.CourseScoringRankingAdapter;
import com.dayaokeji.rhythmschoolstudent.client.home.course.services.CourseScoringService;
import com.dayaokeji.rhythmschoolstudent.utils.AndroidUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ObjectUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.rhythmschoolstudent.wiget.WrapLinearLayoutManager;
import com.dayaokeji.server_api.domain.Course;
import com.dayaokeji.server_api.domain.CourseScoringRank;
import com.dayaokeji.server_api.domain.UserInfo;

import java.util.List;

import butterknife.BindView;
import io.reactivex.functions.Consumer;

/**
 * 评学排行
 */
public class CourseScoringRankingActivity extends BaseActivity {

    private static final String COURSE_DETAIL = "course_detail";

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rv_course_scoring_ranking)
    RecyclerView rvCourseScoringRanking;

    private final CourseScoringRankingAdapter courseScoringRankingAdapter = new CourseScoringRankingAdapter();
    private Course course;

    public static void navigation(Context context, Course course) {
        if (context == null) return;
        Intent intent = new Intent(context, CourseScoringRankingActivity.class);
        intent.putExtra(COURSE_DETAIL, course);
        ActivityCompat.startActivity(context, intent, null);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_course_scoring_ranking);
        setSupportActionBar(toolbar);
        course = (Course) getIntent().getSerializableExtra(COURSE_DETAIL);
        init();
    }

    private void init() {
        setupView();
        setupViewData();
    }

    private void setupView() {
        rvCourseScoringRanking.setLayoutManager(new WrapLinearLayoutManager(this));
        rvCourseScoringRanking.setAdapter(courseScoringRankingAdapter);
    }

    private void setupViewData() {
        ActionBar supportActionBar = getSupportActionBar();
        if (supportActionBar != null) {
            supportActionBar.setTitle(course.getName()+"-排行");
        }
        // find course score and rank list
        addDisposable(CourseScoringService.getInstance().findCourseScoringRanks(course.getCourseDetailId()).subscribe(courseSoringRankingsConsumer));
    }

    private Consumer<List<CourseScoringRank>> courseSoringRankingsConsumer = (courseScoringRanks -> {
        if (courseScoringRanks != null) {
            courseScoringRankingAdapter.setNewData(courseScoringRanks);
            setCurrentUserRank(courseScoringRanks);
        }
    });

    private void setCurrentUserRank(List<CourseScoringRank> rankList) {
        // current user rank
        UserInfo userInfo = UserUtils.getUserInfo();
        if (userInfo == null) return ;
        if (TextUtils.isEmpty(userInfo.getId())) return ;
        for (CourseScoringRank courseScoringRank : rankList) {
            Integer userId = courseScoringRank.getUserId();
            if (ObjectUtils.equals(String.valueOf(userId),userInfo.getId())) {
                courseScoringRankingAdapter.addHeaderView(buildCurrentUserRankingView(courseScoringRank));
                courseScoringRankingAdapter.addHeaderView(buildHeaderLineView());
            }
        }
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        getMenuInflater().inflate(R.menu.course_scoring_ranking, menu);
//        return super.onCreateOptionsMenu(menu);
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        switch (item.getItemId()) {
//            case R.id.menu_view_semester_rank: // 查看学期排行
//
//                break;
//        }
//        return super.onOptionsItemSelected(item);
//    }



    /**
     * 当前用户Item
     *
     * @param courseScoringRank
     */
    private View buildCurrentUserRankingView(CourseScoringRank courseScoringRank) {
        View rankingView = LayoutInflater.from(this).inflate(R.layout.item_course_scoring_ranking, null, false);
        TextView tvRanking = rankingView.findViewById(R.id.tv_ranking);
        ImageView ivUserAvatar = rankingView.findViewById(R.id.iv_user_avatar);
        TextView tvUserName = rankingView.findViewById(R.id.tv_user_name);
        TextView tvCollege = rankingView.findViewById(R.id.tv_college);
        TextView tvCourseScore = rankingView.findViewById(R.id.tv_course_score);
        rankingView.findViewById(R.id.iv_item_allow).setVisibility(View.VISIBLE);
        rankingView.findViewById(R.id.view_item_line).setVisibility(View.GONE);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,AndroidUtils.dp2px(70));
        rankingView.setLayoutParams(layoutParams);
        ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) tvCourseScore.getLayoutParams();
        params.rightMargin = 0;
        tvCourseScore.setLayoutParams(params);

        // 排名
        Integer rank = courseScoringRank.getRank();
        if (rank != null) {
            tvRanking.setText(String.valueOf(rank));
        }

        // 分值
        String score = courseScoringRank.getScore() == null ? "--" : String.valueOf(courseScoringRank.getScore());
        tvCourseScore.setText(score);

        tvCollege.setText(courseScoringRank.getFacultyName()); // 学院
        tvUserName.setText(courseScoringRank.getUserName());
        withGlide().load(ApiConstantKt.getRemoteImageUrl() + courseScoringRank.getResourceId()).into(ivUserAvatar);
        return rankingView;
    }

    /**
     * current item next line
     *
     * @return
     */
    private View buildHeaderLineView() {
        View view = new View(this);
        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, AndroidUtils.dp2px(20));
        view.setLayoutParams(layoutParams);
        view.setBackgroundColor(getResources().getColor(R.color.window_background));
        return view;
    }
}
